
package com.kugou.game.sdk.ui.activity;

import com.kugou.framework.base.LogUtil;
import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.BaseSDKConfig;
import com.kugou.game.sdk.api.common.IEventCode;
import com.kugou.game.sdk.api.common.IEventDataField;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.PlatformEventDispatcher;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnLoginListener;
import com.kugou.game.sdk.ui.dialog.AllUserDialog;
import com.kugou.game.sdk.ui.dialog.AllUserDialog.OnDeleteUserListener;
import com.kugou.game.sdk.ui.dialog.AllUserDialog.OnSelectUserListener;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.os.Process;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述:登录界面
 * 
 * @author liux
 * @since 2013-12-13 下午08:05:38
 */
public class LoginActivity extends BaseCommonTitleFragmentActivity {
    private int mFrom;// 来自哪个页面

    private User user;// 当前是那个用户

    /**
     * 登录请求和结果消息指令
     */
    private final int MSG_LOGIN = 10;

    protected static final int MSG_LOGIN_SUCCESS = 20;

    protected static final int MSG_LOGIN_FAIL = 30;

    /**
     * 界面控件
     */
    private TextView payLoginForgotPassword, mWrongTips;

    private LoadingView mLoadingView;

    private EditText mNickName;

    private EditText mPassword;

    private Button mLogin;

    private Button mRegister;

    private ImageView mAccountSelect;

    private LinearLayout mloginLayout;

    private ScrollView mLayoutScrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int layoutId;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.PORTRAIT) {
            layoutId = Rx.layout.kg_login_activity;
        } else {
            layoutId = Rx.layout.kg_login_activity_land;
        }
        if (layoutId != 0) {
            setContentView(layoutId);
            mFrom = getIntent().getIntExtra(FROM_ACTION_KEY, FROM_NORMAL);
            String nickName = getIntent().getStringExtra(USER_NICKNAME_KEY);
            String password = getIntent().getStringExtra(USER_PASSWORD_KEY);
            // 设置标题
            setCommonTitle(Rx.string.kg_game_center);
            // 初始化界面
            initViews();

            if (!TextUtils.isEmpty(nickName) && !TextUtils.isEmpty(password)) {// 如果跳转进来有传入用户名密码，则显示传入的用户信息
                mNickName.setText(nickName);
                mPassword.setText(password);
            } else {// 否则，显示最新登录用户的信息。如从重置密码跳转过来
                user = UserManager.getInstance().getLastestUserDataOnSPAndSDcard();
                if (user != null) {
                    if (user.isRegistered()) {
                        mNickName.setText(user.getAccountName());
                        if (TextUtils.isEmpty(user.getPassword())) {
                            mPassword.setText(user.getKugouToken());
                        } else {
                            mPassword.setText(user.getPassword());
                        }
                    } else {
                        // 临时账号，不显示账号密码
                        mNickName.setText("");
                        mPassword.setText("");
                    }
                }
            }
            IntentFilter filter = new IntentFilter();
            filter.addAction(SDKActions.ACTION_GET_NEW_PASSWORD);
            registerReceiver(mReceiver, filter);
        } else {
            showToast(Rx.string.kg_layout_not_found);
        }
    }

    /**
     * 初始化界面控件
     */
    private void initViews() {
        mLoadingView = (LoadingView) findViewById(Rx.id.kg_loading);
        mLoadingView.setText("正在登录，请稍候...");
        // 登录信息
        int payloginScrollViewID = Rx.id.kg_layout_scrollview;
        mLayoutScrollView = (ScrollView) findViewById(payloginScrollViewID);
        int payLayoutUserloginID = Rx.id.kg_layout_userlogin;
        mloginLayout = (LinearLayout) findViewById(payLayoutUserloginID);
        // 用户名
        mNickName = (EditText) findViewById(Rx.id.kg_login_username);
        // 提示信息
        mWrongTips = (TextView) findViewById(Rx.id.kg_login_wrong_tips);

        mNickName.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    checkUserName();
                }
            }
        });

        mNickName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    // 打开日志开关
                    if (AppUtil.turnOnLogSwitch(s.toString())) {
                        showToast("turn on log...");
                        AppUtil.gatherDebugInfo(LoginActivity.this);
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    mPassword.setText("");
                }
            }
        });

        // 密码
        mPassword = (EditText) findViewById(Rx.id.kg_login_password);
        mPassword.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    checkPassword();
                }
            }
        });

        // 选择账号下拉按钮
        int mAccountSelectId = Rx.id.kg_account_select;
        mAccountSelect = (ImageView) findViewById(mAccountSelectId);
        ArrayList<User> mAllUsers = UserManager.getInstance().getAllRegistedUsers();
        if (mAllUsers == null || mAllUsers.size() == 0) {
            mAccountSelect.setVisibility(View.GONE);
        } else {
            mAccountSelect.setVisibility(View.VISIBLE);
        }
        mAccountSelect.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showUsesDialog();
            }
        });
        // 登录按钮
        mLogin = (Button) findViewById(Rx.id.kg_start_login_button);
        mLogin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!checkAllInputInfo())
                    return;

                int gameType = SDKControler.getGameType();
                User user = UserManager.getInstance().getCurrentUserInternal();
                if (user != null && !user.isRegistered()
                        && gameType == BaseSDKConfig.GAME_TYPE_SINGLE) {
                    showSingleTempChangeAccount();
                } else {
                    boolean needReboot = SDKControler.isNeedRestartWhenAccountChanged();
                    if (needReboot && mFrom == FROM_CHANGE_ACCOUNT) {
                        showRebootDialog();
                    } else {
                        login();
                    }
                }

            }
        });
        // 注册按钮
        mRegister = (Button) findViewById(Rx.id.kg_start_reg_imdi_button);
        mRegister.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });
        // 忘记密码
        int payLoginForgotPasswordID = Rx.id.kg_login_forgot_password;
        payLoginForgotPassword = (TextView) findViewById(payLoginForgotPasswordID);
        payLoginForgotPassword.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getBackPassword();
            }
        });

        // 如果从巨炮游戏中心跳入，隐藏一些入口
        if (mFrom == FROM_GAME_CENTER) {
            payLoginForgotPassword.setVisibility(View.INVISIBLE);
            mRegister.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 点击登录按钮
     */
    private void login() {
        if (checkAllInputInfo()) {
            if (!NetWorkUtil.isNetworkAvailable(this)) {
                showToast("请检查您的网络连接");
                return;
            }

            hideSoftInput(this);
            mloginLayout.setVisibility(View.GONE);
            mLayoutScrollView.setVisibility(View.GONE);
            mLoadingView.setVisibility(View.VISIBLE);
            // 发送登录请求
            sendEmptyBackgroundMessage(MSG_LOGIN);
        }
    }

    /**
     * 跳转到注册页面
     */
    private void register() {
        hideSoftInput(this);
        Intent intent = new Intent(this, RegisterByPhoneActivity.class);
        intent.putExtra(FROM_ACTION_KEY, mFrom);
        startActivity(intent);
    }

    /**
     * 跳转到找回密码页面
     */
    private void getBackPassword() {
        hideSoftInput(this);
        Intent intent = new Intent(LoginActivity.this, GetBackPasswordActivity.class);
        intent.putExtra(USER_NICKNAME_KEY, mNickName.getText().toString().trim());
        startActivity(intent);
    }

    /**
     * 登录前检查信息格式的正确性
     */
    private boolean checkAllInputInfo() {
        return checkUserName() && checkPassword();
    }

    /**
     * 检查账号
     * 
     * @return
     */
    private boolean checkUserName() {
        String str = mNickName.getText().toString();
        if (TextUtils.isEmpty(str)) {
            mWrongTips.setVisibility(View.VISIBLE);
            mWrongTips.setText("用户名不能为空");
        }
        // else if (!isUserNameCorrect(str)) {
        // mWrongTips.setVisibility(View.VISIBLE);
        // mWrongTips.setText("您输入的用户名有误，请重新输入");
        // }
        else {
            mWrongTips.setVisibility(View.INVISIBLE);
            return true;
        }
        return false;
    }

    /**
     * 检查密码
     * 
     * @return
     */
    private boolean checkPassword() {
        String str = mPassword.getText().toString();
        if (TextUtils.isEmpty(str)) {

            mWrongTips.setVisibility(View.VISIBLE);
            mWrongTips.setText("密码不能为空");
        } else if (!isPasswordCorrect(str)) {
            mWrongTips.setVisibility(View.VISIBLE);
            mWrongTips.setText("您输入的密码有误，请重新输入");
        } else {
            mWrongTips.setVisibility(View.INVISIBLE);
            return true;
        }
        return false;
    }

    /**
     * 判断账号是否符合格式要求
     * 
     * @param userName
     * @return
     */
    private boolean isUserNameCorrect(String userName) {
        if (!TextUtils.isEmpty(userName)) {
            // Pattern pattern = Pattern.compile("^[0-9a-zA-Z]{4,20}$");
            Pattern pattern = Pattern.compile("^[\\u4e00-\\u9fa5a-zA-Z\\d]{4,20}$");
            Matcher matcher = pattern.matcher(userName);
            return matcher.find();
        }
        return false;
    }

    /**
     * 判断密码是否符合格式要求
     * 
     * @param password
     * @return
     */
    private boolean isPasswordCorrect(String password) {
        if (!TextUtils.isEmpty(password)) {
            Pattern pattern = Pattern.compile("^[0-9a-zA-Z]{6,16}$");
            Matcher matcher = pattern.matcher(password);
            if (matcher.find()) {
                return true;
            }
            // 改为token也可以登陆
            String userName = mNickName.getText().toString();
            if (user != null && userName.equals(user.getAccountName())
                    && password.equals(user.getKugouToken())) {
                // 使用token登陆
                return true;
            }
        }
        return false;
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        switch (msg.what) {
            case MSG_LOGIN:
                String userName = mNickName.getText().toString();
                String password = mPassword.getText().toString();
                long appId = SDKControler.getAppId();
                int source = 0;
                long tAppId = 0;
                if (user != null && userName.equals(user.getAccountName())
                        && password.equals(user.getKugouToken())) {
                    // 使用token登陆
                    source = 1;
                    tAppId = user.getKugouTokenAppId();
                } else {
                    // 使用密码登陆
                    source = 0;
                }
                final Message myMsg = new Message();
                UserManager.getInstance().login(userName, password, appId, source, tAppId,
                        new OnLoginListener() {
                            @Override
                            public void onSuccess(User user) {
                                if (SDKControler.getGameType() == BaseSDKConfig.GAME_TYPE_ONLINE) {
                                    AppUtil.writeDataToSSO(user);
                                }
                                myMsg.obj = user;
                                myMsg.what = MSG_LOGIN_SUCCESS;
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                myMsg.obj = errorMsg;
                                myMsg.what = MSG_LOGIN_FAIL;
                            }

                        });

                sendUiMessage(myMsg);
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        switch (msg.what) {
            case MSG_LOGIN_SUCCESS:// 登录成功
                User user = (User) msg.obj;

                // AppCenterSDK.setUserName(user.getNickName());

                Bundle bundle = new Bundle();
                if (mFrom == FROM_CHANGE_ACCOUNT) {// 来自切换账号，根据配置决定是否重启
                    boolean isReboot = SDKControler.isNeedRestartWhenAccountChanged();
                    bundle.putSerializable(IEventDataField.EXTRA_USER, user);

                    PlatformEventDispatcher
                            .sendEventNow(IEventCode.ACCOUNT_CHANGED_SUCCESS, bundle);
                    AppUtil.handleActionsAfterLoginSuccess(IEventCode.ACCOUNT_CHANGED_SUCCESS);

                    LogUtil.d("callback", "LoginActivity:ACCOUNT_CHANGED_SUCCESS");
                    if (isReboot) {// 重启游戏
                        PlatformEventDispatcher.sendEventNow(IEventCode.INTENT_TO_REBOOT_APP,
                                bundle);
                        LogUtil.d("callback", "LoginActivity:INTENT_TO_REBOOT_APP");
                        reStart();
                    } else {// 返回游戏
                        sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
                    }
                } else if (mFrom == FROM_RECHARGE) {// 来自充值，返回充值
                    Intent intent = new Intent(LoginActivity.this, RechargeActivity.class);
                    intent.putExtra(USER_NICKNAME_KEY, user.getAccountName());
                    startActivity(intent);
                    finish();
                } else if (mFrom == FROM_GAME_CENTER) {// 来自巨炮游戏中心
                    sendBroadcast(new Intent(SDKActions.ACTION_LOGIN_SUCCESS));
                    finish();
                } else {// 来自正常登录，返回游戏
                        // 发送回调事件给用户
                    bundle.putSerializable(IEventDataField.EXTRA_USER, user);
                    PlatformEventDispatcher.sendEvent(IEventCode.ENTER_GAME_SUCCESS, bundle);
                    AppUtil.handleActionsAfterLoginSuccess(IEventCode.ENTER_GAME_SUCCESS);
                    LogUtil.d("callback", "LoginActivity:ENTER_GAME_SUCCESS");

                    // 通知关闭所有SDK页面
                    sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
                    finish();

                }
                break;
            case MSG_LOGIN_FAIL:// 登录失败
                mLoadingView.setVisibility(View.GONE);
                mLayoutScrollView.setVisibility(View.VISIBLE);
                mloginLayout.setVisibility(View.VISIBLE);

                String errorMsg = (String) msg.obj;
                // showToast(errorMsg);
                mWrongTips.setVisibility(View.VISIBLE);
                mWrongTips.setText(TextUtils.isEmpty(errorMsg) ? "未知错误" : errorMsg);
                break;

        }
    };

    private void showUsesDialog() {
        AllUserDialog allUserDialog = new AllUserDialog(LoginActivity.this);
        allUserDialog.setContentView(Rx.layout.kg_all_user_dialog);
        allUserDialog.setOnSelectUserListener(new OnSelectUserListener() {

            @Override
            public void afterSelectUser(User userData) {
                user = userData;
                mNickName.setText(userData.getAccountName());
                if (TextUtils.isEmpty(user.getPassword())) {
                    mPassword.setText(user.getKugouToken());
                } else {
                    mPassword.setText(user.getPassword());
                }
                mWrongTips.setVisibility(View.INVISIBLE);

            }
        });

        allUserDialog.setOnDeleteUserListener(new OnDeleteUserListener() {

            @Override
            public void afterDeleteUser(int remainSize, String deleteNickName) {
                if (remainSize == 0) {// 对话框中已经没有用户
                    mAccountSelect.setVisibility(View.GONE);
                    mPassword.setText("");
                    mNickName.setText("");
                    user = null;
                } else {
                    // 如果删除的用户是正在显示的用户，则清除，用账号列表第一个用户信息代替
                    if (deleteNickName != null
                            && deleteNickName.equals(mNickName.getText().toString())) {
                        ArrayList<User> allUser = UserManager.getInstance().getAllRegistedUsers();
                        user = allUser.get(0);
                        mNickName.setText(user.getAccountName());
                        if (TextUtils.isEmpty(user.getPassword())) {
                            mPassword.setText(user.getKugouToken());
                        } else {
                            mPassword.setText(user.getPassword());
                        }
                        // 更新最新登录用户为列表的第一个
                        UserManager.getInstance().saveLatestUserData(user);
                    }
                }

            }
        });
        allUserDialog.setEditFlag(false);
        ArrayList<User> users = UserManager.getInstance().getAllRegistedUsers();
        if (users != null && users.size() > 0) {
            allUserDialog.clearDatas();
            allUserDialog.addDatas(users);
            allUserDialog.setCurrentUser(mNickName.getText().toString());
            allUserDialog.notifyAdapterChage();
        }
        allUserDialog.show();
    }

    private void showRebootDialog() {
        final BaseConfirmDialog rebootConfirmDialog = new BaseConfirmDialog(LoginActivity.this);
        rebootConfirmDialog.setMessage(Rx.string.kg_dialog_reboot_confirm);
        rebootConfirmDialog.setOKClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                rebootConfirmDialog.dismiss();
                login();
            }
        });
        rebootConfirmDialog.show();
    }

    private void showSingleTempChangeAccount() {
        final BaseConfirmDialog dialog = new BaseConfirmDialog(LoginActivity.this);
        dialog.setMessage(Rx.string.kg_singe_temp_account_change_warn);
        dialog.setOKBtnText("立即注册");
        dialog.setCancelText("是");
        dialog.setCancelClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                boolean needReboot = SDKControler.isNeedRestartWhenAccountChanged();
                if (needReboot && mFrom == FROM_CHANGE_ACCOUNT) {
                    showRebootDialog();
                } else {
                    login();
                }
            }
        });
        dialog.setOKClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
                dialog.dismiss();

            }
        });
        dialog.show();
    }

    /**
     * 重启游戏
     */
    private void reStart() {
        AppUtil.gc();
        finish();
        clearAllActivityAndRestart();
        Process.killProcess(Process.myPid());
    }

    /**
     * 清除所有页面并重新启动应用
     */
    private void clearAllActivityAndRestart() {
        Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(
                getBaseContext().getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }

    /**
     * 点击返回按钮，关闭页面之前发送回调事件给用户
     */
    @Override
    protected void onBackBtnClick() {
        exitLoginPage();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                exitLoginPage();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出登录界面
     */
    private void exitLoginPage() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }

    /**
     * 修改密码广播接收器
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (SDKActions.ACTION_GET_NEW_PASSWORD.equals(action)) {
                String userName = intent.getStringExtra(USER_NICKNAME_KEY);
                String newPassword = intent.getStringExtra(USER_PASSWORD_KEY);
                mNickName.setText(TextUtils.isEmpty(userName) ? "" : userName);
                mPassword.setText(TextUtils.isEmpty(newPassword) ? "" : newPassword);
            }
        }
    };
}
